﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using nRoute.Navigation.Containers;

namespace nRoute.Samples.Netflix.Behaviors
{
    public class NavigateBackInfoBehavior
        : Behavior<TextBlock>
    {
        private const string DEFAULT_TITLE = null;
        private const string ECLIPSE = "..";

        public static readonly DependencyProperty BrowsingContainerProperty =
           DependencyProperty.Register("BrowsingContainer", typeof(IBrowsingContainer), typeof(NavigateBackInfoBehavior),
           new PropertyMetadata(null, new PropertyChangedCallback(BrowsingContainerChanged)));

        public IBrowsingContainer BrowsingContainer
        {
            get { return (IBrowsingContainer)(GetValue(BrowsingContainerProperty)); }
            set { SetValue(BrowsingContainerProperty, value); }
        }

        protected override void OnAttached()
        {
            base.OnAttached();
            UpdateContent();
        }

#region Handler

        private static void BrowsingContainerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((NavigateBackInfoBehavior)d).UpdateContainer((IBrowsingContainer)e.OldValue, (IBrowsingContainer)e.NewValue);
        }

        private void Container_Navigated(object sender, NavigatedEventArgs e)
        {
            UpdateContent();
        }

#endregion

#region Helper

        private void UpdateContainer(IBrowsingContainer oldContainer, IBrowsingContainer newContainer)
        {
            if (oldContainer != null) oldContainer.Navigated -= new EventHandler<NavigatedEventArgs>(Container_Navigated);
            if (newContainer != null) newContainer.Navigated += new EventHandler<NavigatedEventArgs>(Container_Navigated);
        }

        private void UpdateContent()
        {
            if (this.AssociatedObject == null) return;
            if (this.BrowsingContainer != null)
            {
                //this.AssociatedObject.IsEnabled = this.BrowsingContainer.CanNavigateBack;                
                this.AssociatedObject.Text = ResolveTitle(this.BrowsingContainer.BackPagesJournal.FirstOrDefault());
            }
            else
            {
                this.AssociatedObject.Text = null;
                //this.AssociatedObject.IsEnabled = false;
            }
        }

        private string ResolveTitle(PageContentState state)
        {
            if (state == null || string.IsNullOrWhiteSpace(state.Title)) return DEFAULT_TITLE;
            return state.Title; //.Length > 20 ? state.Title.Substring(0, 18).Trim() + ECLIPSE : state.Title;
        }

#endregion

    }
}


